<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <!--        <el-form-item label="工段">-->
        <!--          <el-select-->
        <!--            v-model="searchParam.workshopSectionId"-->
        <!--            placeholder="请选择工段"-->
        <!--            clearable-->
        <!--            filterable-->
        <!--            @change="changeWorkshopSection"-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="item in workshopSectionList"-->
        <!--              :key="item.id"-->
        <!--              :label="item.workshopSectionCode"-->
        <!--              :value="item.id"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="工序">
          <el-select
            v-model="searchParam.processId"
            placeholder="请选择工序"
            clearable
            filterable
            @change="processChange"
          >
            <el-option
              v-for="item in processList"
              :key="item.id"
              :label="item.processCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产线">
          <el-select
            v-model="searchParam.processEquipId"
            placeholder="请选择生产线"
            clearable
            filterable
            @change="processEquipChange"
          >
            <el-option
              v-for="item in processEquipList"
              :key="item.id"
              :label="item.equipCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备">
          <el-select
            v-model="searchParam.equipId"
            placeholder="请选择设备"
            clearable
            filterable
            @change="equipChange"
          >
            <el-option
              v-for="item in equipList"
              :key="item.equipId"
              :label="item.equipName"
              :value="item.equipId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态">
          <el-select
            v-model="searchParam.workOrderStatus"
            placeholder="请选择工单状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('PsmOrderStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工单时间">
          <el-date-picker
            v-model="searchParam.collectionTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getcollectionTime"
          />
        </el-form-item>
        <el-form-item label="报警等级">
          <el-select
            v-model="searchParam.alarmLevel"
            placeholder="请选择报警等级"
            clearable
          >
            <el-option
              v-for="item in useDictionary('ScaAlarmLevel')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="resetHandle">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <!--      <template #header>-->
      <!--        <el-button type="success" plain @click="openDialog()"><i-ep-plus />新增</el-button>-->
      <!--                -->
      <!--      </template>-->

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        :maxHeight="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="工单状态"
          prop="workOrderStatus"
          min-width="80"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              useDictionary("PsmOrderStatus", scope.row.workOrderStatus) || ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="工单生成时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="最近一次处理时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="工段"
          prop="workshopSectionCode"
          min-width="80"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="工序"
          prop="processCode"
          min-width="80"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="生产线"
          prop="processEquipCode"
          min-width="80"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="设备"
          prop="equipName"
          min-width="130"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="报警等级"
          prop="alarmLevel"
          min-width="130"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("ScaAlarmLevel", scope.row.alarmLevel) || "" }}
          </template>
        </el-table-column>
        <el-table-column
          label="运行参数"
          prop="parameterDesc"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
              >
                <i-ep-search />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="处理"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialog(scope.row)"
              >
                <i-ep-edit />
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <esmworkorder-edit
      :key="dayjsValue"
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import {
  useTable,
  useDownload,
  useDictionary,
  useComputeTableHeight,
} from "@/utils/useTable";
import request from "@/utils/request";
import {
  getMdmProcessEquipApi,
  getMdmprocessListApi,
  getMdmproductinfosApi1,
  getMdmProcessProjectApi,
} from "@/utils/commonData";
import dayjs from "dayjs";
import _ from "lodash-es";
import { authAllPerm } from "@/utils/index";

defineOptions({
  name: "EQUESMESMWORKORDER",
  inheritAttrs: false,
});

// 获取产品型号列表
const productList = ref<any>([]);
async function getProductList() {
  const list: any =
    (await getMdmproductinfosApi1({ deviceId: searchParam.value.equipId })) ||
    [];
  productList.value = [...list];
}

// 请求参数
const requestApi = "/eam/esmworkorder/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  processId: "",
  processCode: "",
  processEquipId: "",
  equipId: "",
  equipCode: "",
  productModel: "",
  projectId: "",
  projectCode: "",
  projectName: "",
  workOrderStatus: "",
  alarmLevel: "",
  programName: "",
  collectionTimeSearch: [],
  collectionTimeStart: "",
  collectionTimeEnd: "",
};

const deleteParam = {
  api: "/eam/esmworkorder/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 定义tableHeight, 将计算注入dataCallBack回调中
const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

onMounted(async () => {
  getTableList();
  await getProcessList();
  await getProcessEquipList();
  await getEquipList();
  // await getProductList();
  await getProjectList();
  getProductModelList();
  getWorkshopSectionList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/esmworkorder/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

const dayjsValue = ref(dayjs().valueOf());
/** 打开工单管理表单弹窗 */
function openDialog(roleObj?: Object) {
  dayjsValue.value = dayjs().valueOf();
  if (roleObj) {
    addDialog.title = "修改工单管理";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增工单管理";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开工单管理表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "工单管理详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getcollectionTime(data: any) {
  if (data) {
    searchParam.value.collectionTimeStart = data[0];
    searchParam.value.collectionTimeEnd = data[1];
  } else {
    searchParam.value.collectionTimeStart = "";
    searchParam.value.collectionTimeEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/esmworkorder/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
// 获取工序列表
const processList = ref<any>([]);
async function getProcessList() {
  processList.value = (await getMdmprocessListApi({})) || [];
}
async function processChange(id: string) {
  searchParam.value.equipId = "";
  searchParam.value.equipCode = "";
  searchParam.value.productModel = "";
  searchParam.value.processEquipId = "";
  if (id) {
    const current: any =
      processList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.processCode = current.processCode || "";
  } else {
    searchParam.value.processCode = "";
  }
  getProcessEquipList();
  getEquipList();
}

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList() {
  const { data } = await request({
    // url: "iotadmin/scaequipinfo/getList",
    // method: "post",
    // data: {},
    url: "/dmpDosPcm/equipmentInfo/getList",
    method: "post",
    data: {
      processCode: searchParam.value.processCode,
      processId: searchParam.value.processId,
      workshopSectionId: searchParam.value.workshopSectionId,
      processEquipId: searchParam.value.processEquipId,
    },
  });
  equipList.value = data || [];
}
function equipChange(id: string) {
  searchParam.value.productModel = "";
  if (id) {
    const current: any =
      equipList.value?.filter((e: any) => e.id === id)[0] ?? {};
    searchParam.value.equipCode = current.equipCode || "";
    getProductList();
  } else {
    searchParam.value.equipCode = "";
    getProductList();
  }
}

// 获取项目列表
const projectList = ref([]);
const getProjectList = async () => {
  await request({
    url: `mdm/mdmprojectinfo/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    projectList.value = res.data;
  });
};
// 改变项目列表
const changeProject = (e: string) => {
  productModelList.value = [];
  filteredOptions.value = [];
  searchParam.value.productModel = "";
  if (e) {
    const current: any =
      projectList.value?.filter((item) => item.id == e)[0] ?? {};
    searchParam.value.projectName = current.projectName;
    searchParam.value.projectCode = current.projectCode;
    getProductModelList(e);
  } else {
    searchParam.value.projectName = "";
    searchParam.value.projectCode = "";
    getProductModelList();
  }
};

// 根据项目获取产品型号
// 获取产品型号
const productModelList = ref([]);
const filteredOptions = ref([]);
const getProductModelList = async (id?: string) => {
  await request({
    url: "mdm/mdmproductinfo/getList",
    method: "post",
    data: { projectId: id || "" },
  }).then((res) => {
    productModelList.value = res.data;
    filteredOptions.value = [...productModelList.value];
  });
};

// 使用 debounce 包装过滤方法
const customFilter = _.debounce((query) => {
  if (!query) {
    filteredOptions.value = [...productModelList.value];
    return;
  }
  filteredOptions.value = productModelList.value.filter((option: any) =>
    option.productCode.toLowerCase().includes(query.toLowerCase())
  );
}, 300);

const workshopSectionList = ref([]);
const getWorkshopSectionList = async () => {
  await request({
    url: `mdm/mdmworkshopsection/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    workshopSectionList.value = res.data;
  });
};
const changeWorkshopSection = () => {
  searchParam.value.processEquipId = "";
  searchParam.value.processId = "";
  searchParam.value.equipId = "";
  searchParam.value.productModel = "";
  processList.value = [];
  getProcessListByWorkshopSection();
  getProcessEquipList();
  getEquipList();
};
const getProcessListByWorkshopSection = async () => {
  if (searchParam.value.workshopSectionId) {
    await request({
      url: `mdm/mdmworkshopsection/getDetails`,
      method: "post",
      data: { id: searchParam.value.workshopSectionId },
    }).then((res) => {
      processList.value = res.data
        ? res.data.map(({ processId, processCode }) => ({
            id: processId,
            processCode,
          }))
        : [];
    });
  } else {
    await getProcessList();
  }
};
function resetHandle() {
  reset();
  getEquipList();
  getProcessList();
  getProductModelList();
  getProcessEquipList();
}

// 获取工序列表
const processEquipList: any = ref([]);
async function getProcessEquipList() {
  searchParam.value.processEquipId = "";
  processEquipList.value = [];
  const { data } = await request({
    // url: `/mdm/mdmprocess/getList`,
    url: "/mdm/mdmprocessequip/getList",
    method: "post",
    data: {
      workshopSectionId: searchParam.value.workshopSectionId,
      processId: searchParam.value.processId,
    },
  });
  processEquipList.value = data;
}
function processEquipChange() {
  getEquipList();
  getProjectList();
  getProductList();
}
</script>
